#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "ERROR:" << "Usage " << argv[0] << " port" << std::endl;
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    //创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd == -1)
    {
        std::cerr << "socket error" << std::endl;
        exit(1);
    }

    //填写目标服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while(true)
    {
        //发送消息
        std::string input;
        std::cout << "Please Enter:";
        std::getline(std::cin, input);
        
        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr*)&server, sizeof server);
        
        //接收消息
        char buff[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        int m = recvfrom(sockfd, buff, sizeof buff - 1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0)
        {
            buff[m] = 0;
            std::cout << buff << std::endl;
        }
    }
    return 0;
}